import {messages} from "share/common";
/**
 * Created by Allen on 2018/1/30.
 */
import React from 'react'
import { connect } from 'react-redux'
import moment from 'moment'
import { Tabs, message, Badge, Alert, Button, Popconfirm, Popover } from 'antd'
import SlideFrame from 'components/slide-frame'
import myAgencyService from 'containers/my-agency/my-agency.service'
import NewAgent from 'containers/my-agency/new-agent'
import NewAgency from 'containers/my-agency/new-agency'
import ResizeTable from 'components/resize-table';
const TabPane = Tabs.TabPane;

class DocumentAgent extends React.Component{
  constructor(props){
    super(props);

    this.state = {
      loading: false,
      loadingApprove: true, //代理审批相关的表单的loading
      loadingApply: true, //代理制单相关的表单的loading
      showSlideFrame: false,
      billApplyOptions: {}, //代理制单全部单据项
      billApproveOptions: {}, //代理审批全部单据项
      data: [],
      nowAgent: {},
      pagination: {
        page: 0,
        total: 0,
        current: 1,
        pageSize: 10,
      },
      status: 'AGENT-MAKE',
      tabs: [
        {key: 'AGENT-MAKE', name: messages('my-agency.key43')/*我的代理人【制单】*/},
        {key: 'AGENCY-MAKE', name: messages('my-agency.key44')/*我的代理【制单】*/},
        {key: 'AGENT', name: messages('my-agency.key1'/*我的代理人【审批】*/)}, //我的代理人
        {key: 'AGENCY', name: messages('my-agency.key2'/*我的代理【审批】*/)} //我的代理
      ],
      columnGroup: {
        agency: [
          {
            title: messages('my-agency.key3'/*授权人姓名*/),
            dataIndex: 'principalUserDTO.fullName',
            key: 'fullName', width: '15%'
          }, //授权人姓名
          {
            title: messages('my-agency.key4'/*授权人工号*/),
            dataIndex: 'principalUserDTO.employeeID',
            key: 'employeeID', width: '15%'
          }, //授权人工号
          {
            title: messages('my-agency.key5'/*代理日期*/),
            dataIndex: 'agentDate',
            key: 'agentDate', width: '30%'
          }, //代理日期
          {
            title: messages('my-agency.key6'/*代理单据*/),
            dataIndex: 'customFormDTOs',
            key: 'customFormDTOs', width: '30%',
            render: (values, record) => this.renderFormData(values, record)
          }, //代理单据
          {
            title: messages('common.column.status'),
            dataIndex: 'enabled',
            key: 'enabled', width: '10%',
            render: enabled => (
              <Badge status={enabled ? 'success' : 'error'}
                   text={ enabled ? messages('my-agency.key7'/*生效中*/) : messages('my-agency.key8'/*已失效*/)}/>)
            }, //状态
        ],
        agentEditable: [
          {
            title: messages('my-agency.key9'/*姓名*/),
            dataIndex: 'proxyUserDTO.fullName',
            key: 'fullName2', width: '10%'
          }, //姓名
          {
            title: messages('my-agency.key10'/*工号*/),
            dataIndex: 'proxyUserDTO.employeeID',
            key: 'employeeID2', width: '10%'
          }, //工号
          {
            title: messages('my-agency.key5'/*代理日期*/),
            dataIndex: 'agentDate',
            key: 'agentDate', width: '22%',
          }, //代理日期
          {
            title: messages('my-agency.key6'/*代理单据*/),
            dataIndex: 'customFormDTOs',
            key: 'customFormDTOs', width: '30%',
            render: (values, record) => this.renderFormData(values, record)
          }, //代理单据
          {
            title: messages('common.column.status'),
            dataIndex: 'enabled',
            key: 'enabled', width: '10%',
            render: (value,record) => (
              <Badge status={value === true ? 'success' : 'error'}
                   text={ value === true ? messages('my-agency.key7'/*生效中*/) : messages('my-agency.key8'/*已失效*/)}/>)
          }, //状态
          {
            title: messages('common.operation')/*操作(*/,
            dataIndex: 'operate',
            width: '10%',
            render: (text,record) => (
              <span>
                <a onClick={(e) => this.handleEdit(e, record)}>{messages('common.edit')}</a>
                <span className="ant-divider" />
                <Popconfirm placement="topLeft" onConfirm={(e) => this.handleDelete(e, record)} title={messages('my-agency.key11'/*你确认要删除？*/)}>{/* 你确定要删除organizationName吗 */}
                  <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')}</a>
                </Popconfirm>
              </span>
          )}
        ],
        agentDiseditable: [
          {
            title: messages('my-agency.key9'/*姓名*/),
            dataIndex: 'proxyUserDTO.fullName',
            key: 'fullName2', width: '10%'
          }, //姓名
          {
            title: messages('my-agency.key10'/*工号*/),
            dataIndex: 'proxyUserDTO.employeeID',
            key: 'employeeID2', width: '10%'
          }, //工号
          {
            title: messages('my-agency.key5'/*代理日期*/),
            dataIndex: 'agentDate',
            key: 'agentDate', width: '22%',
          }, //代理日期
          {
            title: messages('my-agency.key6'/*代理单据*/),
            dataIndex: 'customFormDTOs',
            key: 'customFormDTOs', width: '30%',
            render: (values, record) => this.renderFormData(values, record)
          }, //代理单据
          {
            title: messages('common.column.status'),
            dataIndex: 'enabled',
            key: 'enabled', width: '10%',
            render: (value,record) => (
              <Badge status={value ? 'success' : 'error'}
                   text={value ? messages('my-agency.key7'/*生效中*/) : messages('my-agency.key8'/*已失效*/)}/>
            )
          }, //状态
        ]
      }

    }
  }

  componentWillMount(){
    const { profile } = this.props;
    this.getApproveBills();//获取代理审批相关的表单
    this.getApplyBills();//获取代理制单相关的表单
    this.setState({
      status: 'AGENT-MAKE',
      columns: profile['All.AgentApply.Editable'] ? this.state.columnGroup.agentEditable : this.state.columnGroup.agentDiseditable
    }, () => {
      this.getMyAgentList();
    });
  }

  renderFormData = (values, record) => {
    let formList = [];
    values && values.map(item => {
      formList.push(item.formName);
    });
    let formStr = formList.join(', ');
    return record.proxyFormScope === 1002 ? (
      <Popover placement="topLeft" content={formStr}>
        <div style={{overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace:'nowrap', maxWidth: '350px'}}>
          {formStr}
        </div>
      </Popover>
    ) : <span>{messages('common.all')}</span>
  };

  //获取所有代理审批单据项
  getApproveBills(){
    let bill1Options = [];
    let bill2Options = [];
    let bill3Options = [];
    Promise.all([
      myAgencyService.getProxyBills(1001), //申请单
      myAgencyService.getProxyBills(1002), //报销单
      myAgencyService.getProxyBills(3001) //借款单
    ]).then(res => {
      res[0].data.map(item => {
        bill2Options.push(item);
      });
      res[1].data.map(item => {
        bill1Options.push(item);
      });
      res[2].data.map(item => {
        bill3Options.push(item);
      });
      this.setState({
        loadingApprove: false, //代理审批相关的表单加载完毕
        billApproveOptions: {
          expenseBills: bill1Options,
          requestBills: bill2Options,
          loanBills: bill3Options
        }
      });
    });
  };

  //获取所有代理制单单据项
  getApplyBills(){
    let bill1Options = [];
    let bill2Options = [];
    let bill3Options = [];
    Promise.all([
      myAgencyService.getProxyApplyBills(1001), //申请单
      myAgencyService.getProxyApplyBills(1002), //报销单
      myAgencyService.getProxyApplyBills(3001) //借款单
    ]).then(res => {
      res[0].data.map(item => {
        bill2Options.push(item);
      });
      res[1].data.map(item => {
        bill1Options.push(item);
      });
      res[2].data.map(item => {
        bill3Options.push(item);
      });
      this.setState({
        loadingApply: false, //代理制单相关的表单加载完毕
        billApplyOptions: {
          expenseBills: bill1Options,
          requestBills: bill2Options,
          loanBills: bill3Options
        }
      });
    });
  };

  getMyAgencyList(){
    const { status } = this.state;
    const { page, pageSize } = this.state.pagination;
    let operationCode = status === 'AGENCY' ? 2 : 1;
    this.setState({loading: true});
    myAgencyService.getMyAgencyList(page, pageSize, operationCode).then((resp) => {
      resp.data.rows.map(item => {
        item.key = item.principalOID;
        item.agentDate = `${moment(item.startDate).format('YYYY-MM-DD')}——${item.endDate ? moment(item.endDate).format('YYYY-MM-DD') : messages('my-agency.key12'/*无限制*/)}`;
      });
      this.setState({
        loading: false,
        data: resp.data.rows,
        pagination: {
          // showSizeChanger: true,
          // showQuickJumper: true,
          total: Number(resp.data.total),
          page: this.state.pagination.page,
          current: this.state.pagination.current,
          pageSize: this.state.pagination.pageSize,
        }
        });
    }).catch((error) => {
      this.setState({loading: false});
      message.error(messages('common.error'));
    });
  }

  getMyAgentList(){
    const { status } = this.state;
    const { page, pageSize } = this.state.pagination;
    this.setState({loading: true});
    let operationCode = status === 'AGENT' ? 2 : 1;
    myAgencyService.getMyAgentList(page, pageSize, operationCode).then((resp) => {
      resp.data.rows.map(item => {
        if (item.proxyUserDTO.status === 1003){
          item.proxyUserDTO.fullName = `${messages('my-agency.key13'/*离职*/)}-${item.proxyUserDTO.fullName}`;
        }
        item.key = item.proxyOID;
        item.agentDate = `${moment(item.startDate).format('YYYY-MM-DD')}——${item.endDate ? moment(item.endDate).format('YYYY-MM-DD') : messages('my-agency.key12'/*无限制*/)}`;
      });
      this.setState({
        loading: false,
        data: resp.data.rows,
        pagination: {
          // showSizeChanger: true,
          // showQuickJumper: true,
          total: Number(resp.data.total),
          page: this.state.pagination.page,
          current: this.state.pagination.current,
          pageSize: this.state.pagination.pageSize,
        }
      });
    }).catch((error) => {
      this.setState({loading: false});
      message.error(messages('common.error'));
    });
  }


  //点击分页
  onChangePager = (pagination,filters, sorter) => {
    const { status } = this.state;
    if (status === 'AGENCY' || status === 'AGENCY-MAKE'){
      this.setState({
        pagination: {
          total: pagination.total,
          page: pagination.current-1,
          current: pagination.current,
          pageSize: pagination.pageSize
        }
      }, () => {
        this.getMyAgencyList();
      });
    } else if (status === 'AGENT' || status === 'AGENT-MAKE'){
      this.setState({
        pagination: {
          total: pagination.total,
          page: pagination.current-1,
          current: pagination.current,
          pageSize: pagination.pageSize
        }
      }, () => {
        this.getMyAgentList();
      });
    }
  };

  //Tabs点击
  onChangeTabs = (key) => {
    const { profile } = this.props;
    const { agency, agentEditable, agentDiseditable } = this.state.columnGroup;
    let { columns } = this.state;
    if (key === 'AGENCY' || key === 'AGENCY-MAKE') {
      columns = agency;
    } else if (key === 'AGENT') {
      columns = profile['All.AgentApprove.Editable'] ? agentEditable : agentDiseditable;
    } else if (key === 'AGENT-MAKE') {
      columns = profile['All.AgentApply.Editable'] ? agentEditable : agentDiseditable;
    }
    this.setState({
      pagination: {
        page: 0,
        total: 0,
        current: 1,
        pageSize: 10,
      },
      status: key,
      columns
    },()=>{
      const { status } = this.state;
      if (status === 'AGENCY' || status === 'AGENCY-MAKE'){
        this.getMyAgencyList();
      } else if (status === 'AGENT' || status === 'AGENT-MAKE'){
        this.getMyAgentList();
      }
    });
  };

  //渲染Tabs
  renderTabs(){
    const {loading} = this.state;
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key} disabled={loading}/>
      })
    )
  }

  createAgent = () => {
    const { status, billApplyOptions, billApproveOptions } = this.state;
    let billOptions = {};
    if (status === 'AGENT' || status === 'AGENCY') {
      billOptions = billApproveOptions;
    }
    if (status === 'AGENT-MAKE' || status === 'AGENCY-MAKE') {
      billOptions = billApplyOptions;
    }
    this.setState({
      showSlideFrame: true,
      nowAgent: {
        billOptions,
        isNew: true,
        hasInit: false,
        status: status
      }});
  };

  handleEdit = (e,record) => {
    e.stopPropagation();
    const { status, billApplyOptions, billApproveOptions } = this.state;
    let billOptions = {};
    if (status === 'AGENT' || status === 'AGENCY') {
      billOptions = billApproveOptions;
    }
    if (status === 'AGENT-MAKE' || status === 'AGENCY-MAKE') {
      billOptions = billApplyOptions;
    }
    this.setState({
      showSlideFrame: true,
      nowAgent: {
        billOptions,
        isNew: false,
        editFlag: false,
        status: status,
        record: record
      }});
  };

  handleDelete = (e,record) => {

    this.setState({loading: true});
    myAgencyService.deleteAgent(record.ruleOID).then(resp => {
      if (resp.status === 200){
        this.setState({loading: false});
        message.success(messages('my-agency.key14'/*删除成功*/));
        this.getMyAgentList();
      }
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages('common.operate.filed')/*操作失败(*/);
    })
  };

  handleCloseSlide = (success) => {
    const { status } = this.state;
    success && (status === 'AGENT' || status === 'AGENT-MAKE') && this.getMyAgentList();
    success && (status === 'AGENCY' || status === 'AGENCY-MAKE') && this.getMyAgencyList();
    this.setState({ showSlideFrame : false,nowAgent: {}})
  };

  isNewAgency = () => {
    const { status } = this.state;
    const { profile } = this.props;
    if (status === 'AGENCY' || status === 'AGENCY-MAKE') {
      return true;
    }
    if (status === 'AGENT') {
      return profile['All.AgentApprove.Editable'] !== true;
    }
    if (status === 'AGENT-MAKE') {
      return profile['All.AgentApply.Editable'] !== true;
    }
  };

  render(){
    const { loading, data, pagination, showSlideFrame, status, columns, nowAgent, loadingApprove, loadingApply } = this.state;
    const { profile } = this.props;
    return (
      <div>
        <Tabs type="card" defaultActiveKey={status} onChange={this.onChangeTabs} style={{marginTop: -20+'px'}}>
          {this.renderTabs()}
        </Tabs>

        {status === 'AGENCY-MAKE' && (
          <div className="my-agency">
            <Alert message={messages('common.help')/*提示信息*/}
                   description={messages('my-agency.key45')/*你可以在这个页面查看你可以替哪些人【代提】单据*/}
                   type="info"
                   showIcon/>
            <div className="table-header">
              <div className="table-header-title">{messages('common.total', {total: pagination.total})/*共搜索到 {total} 条数据*/}</div>
            </div>
          </div>
        )}

        {status === 'AGENCY' && (
          <div className="my-agency">
            <Alert message={messages('common.help')/*提示信息*/}
                   description={messages('my-agency.key15'/*你可以在这个页面查看 你可以替哪些人【审批】单据*/)}
                   type="info"
                   showIcon/>
            <div className="table-header">
              <div className="table-header-title">{messages('common.total', {total: pagination.total})/*共搜索到 {total} 条数据*/}</div>
            </div>
          </div>
        )}

        {status === 'AGENT-MAKE' && (
          <div className="my-agency">
            {profile['All.AgentApply.Editable'] === true ? (
                <Alert message={messages('common.help')/*提示信息*/}
                       description={messages('my-agency.key46')/*你可以在此页面授权一名员工为你【代提】单据*/}
                       type="info"
                       showIcon/>
              ) : (
                <Alert message={messages('common.help')/*提示信息*/}
                       description={messages('my-agency.key47')/*你可以在此页面查看哪些员工可以为你【代提】单据*/}
                       type="info"
                       showIcon/>
              )}

            <div className="table-header">
              <div className="table-header-title">{messages('common.total', {total: pagination.total})/*共搜索到 {total} 条数据*/}</div>
              {profile['All.AgentApply.Editable'] === true && (
                <Button type="primary" style={{marginBottom: '10px'}} disabled={loadingApprove || loadingApply} onClick={() => this.createAgent()}>{messages('common.create')/*新建*/}</Button>
              )}
            </div>
          </div>
        )}

        {status === 'AGENT' && (
          <div className="my-agency">
            {profile['All.AgentApprove.Editable'] === true ? (
              <Alert message={messages('common.help')/*提示信息*/}
                     description={messages('my-agency.key17'/*你可以在此页面授权一名员工为你【审批】单据*/)}
                     type="info"
                     showIcon/>
            ) : (
              <Alert message={messages('common.help')/*提示信息*/}
              description={messages('my-agency.key18'/*你可以在此页面查看哪些员工可以为你【审批】单据*/)}
              type="info"
              showIcon/>
              )}
            <div className="table-header">
              <div className="table-header-title">{messages('common.total', {total: pagination.total})/*共搜索到 {total} 条数据*/}</div>
              {profile['All.AgentApprove.Editable'] === true && (
                <Button type="primary" style={{marginBottom: '10px'}} disabled={loadingApprove || loadingApply} onClick={() => this.createAgent()}>{messages('common.create')/*新建*/}</Button>
              )}
            </div>
          </div>
        )}
        <ResizeTable
          rowKey={(record, index) => index}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading || loadingApprove || loadingApply}
          scroll={{x: true, y: false}}
          onChange={this.onChangePager}
          onRow={record => ({onClick: (e) => this.handleEdit(e,record)})}
          bordered
          size="middle"/>
        <SlideFrame content={this.isNewAgency() ? NewAgency : NewAgent}
                    title={messages('my-agency.key16'/*代理关系详情*/)}
                    show={showSlideFrame}
                    onClose={()=>this.setState({showSlideFrame:false})}
                    afterClose={this.handleCloseSlide} params={nowAgent}/>
      </div>
    )
  }
}

DocumentAgent.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    main: state.main,
    profile: state.login.profile
  }
}

export default connect(mapStateToProps)(DocumentAgent);
